package com.ruoyi.conf;

import io.minio.MinioClient;
import io.minio.errors.MinioException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
@Validated
@Slf4j
public class MinioConfig {

    @NotBlank
    @Pattern(regexp = "https?://.+", message = "Endpoint must be a valid URL")
    private String endpoint;

    @NotBlank
    private String accessKey;

    @NotBlank
    private String secretKey;

    @NotBlank
    private String bucketName;

    private String alias;
    private String tempUploadDir;
    
    /**
     * 获取公开访问URL的前缀
     * 通过Nginx代理访问，使用域名前缀
     */
//    private String publicUrlPrefix = "https://app1.xyzttkx.site";
//    private String publicUrlPrefix = "https://app1.shuoshuohappy.site";
    private String publicUrlPrefix = "https://app1.shuoshuohappy.site";

    /**
     * 构建公开访问URL
     * @param fileName 文件名
     * @return 完整的访问URL
     */
    public String getPublicUrl(String fileName) {
        return publicUrlPrefix + "/" + bucketName + "/" + fileName;
    }

    /**
     * 初始化 MinioClient Bean，并验证连接是否成功。
     *
     * @return 配置好的 MinioClient 实例
     * @throws MinioException 如果连接失败或初始化过程中出现错误
     */
    @Bean
    public MinioClient minioClient() throws MinioException {
        MinioClient client = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();

        try {
            // 执行一个简单的操作来验证连接，例如列出桶
            List<io.minio.messages.Bucket> buckets = client.listBuckets();
            log.info("MinIO 连接初始化成功。可用的桶数量: {}", buckets.size());
            for (io.minio.messages.Bucket bucket : buckets) {
                log.info("存在的桶: {}", bucket.name());
            }
        } catch (MinioException e) {
            log.error("MinIO 连接初始化失败: {}", e.getMessage(), e);
            throw e; // 抛出异常以防止应用程序在 MinIO 连接失败时继续启动
        } catch (Exception e) {
            log.error("MinIO 连接初始化时发生未知错误: {}", e.getMessage(), e);
            throw new MinioException();
        }

        return client;
    }
}
